package com.xuebusi.controller;


import com.xuebusi.common.ResultModel;
import com.xuebusi.entity.Img;
import com.xuebusi.entity.ImgExample;
import com.xuebusi.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/img")
public class ImgController {

    @Autowired
    private ImgService imgService;

    @RequestMapping(value = "/list")
    public String listImg(Model model) {
        List<Img> list = imgService.selectByExample(new ImgExample());
        model.addAttribute("list", list);
        return "/img/list";
    }

    @RequestMapping(value = "/toUpload")
    public ModelAndView domOtp1() {
        return new ModelAndView("/img/upload");
    }

    @RequestMapping(value = "/getImg/{imgKey}")
    @ResponseBody
    public String getImg(@PathVariable("imgKey") String imgKey) {
        ImgExample imgExample = new ImgExample();
        ImgExample.Criteria criteria = imgExample.createCriteria();
        criteria.andImgKeyEqualTo(imgKey);
        List<Img> list = imgService.selectByExample(imgExample);
        String imgPath = list.get(0).getImgPath();
        return imgPath;
    }

    /**
     * 图片上传
     *
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartHttpServletRequest request) {
        ResultModel<List<Img>> resultModel = imgService.upload(request, "file");
        if (resultModel != null && resultModel.getData() != null) {
            return "上传成功";
        }
        return "上传失败";
    }
}
